package com.meng.spike.controller;

import com.meng.spike.mq.MQProperties;
import com.meng.spike.service.GoodsStoreService;
import com.meng.spike.service.impl.MqService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/")
public class TestController {
    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);


    @Resource
    private GoodsStoreService goodsStoreService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private MQProperties mqProperties;

    private Integer userId = 1;
    @PostConstruct
    private void init(){
        /**
         * 消息发送到交换器Exchange后触发回调。
         * 使用该功能需要开启确认，spring-boot中配置如下：
         * spring.rabbitmq.publisher-confirms = true
         */
        rabbitTemplate.setConfirmCallback((correlationData, b, s) -> {
//            if (b) {
//                System.out.println("消息已确认 cause:{"+s+"} - {"+correlationData+"}");
//            } else {
//                System.out.println("消息未确认 cause:{"+s+"} - {"+correlationData+"}");
//            }
        });
        /**
         * 通过实现ReturnCallback接口，
         * 如果消息从交换器发送到对应队列失败时触发
         * 比如根据发送消息时指定的routingKey找不到队列时会触发
         * 使用该功能需要开启确认，spring-boot中配置如下：
         * spring.rabbitmq.publisher-returns = true
         */
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            LOGGER.error("消息被退回:{}", message);
            LOGGER.error("消息使用的交换机:{}", exchange);
            LOGGER.error("消息使用的路由键:{}", routingKey);
            LOGGER.error("描述:{}", replyText);
        });
    }
    /**
     * 进入测试页面
     * @param model
     * @return
     */
    @GetMapping("")
    public String Index(Model model){
        return "index";
    }

    /**
     * 选课提交
     * @param code
     * @param num
     * @return
     */
    @PostMapping("secKill")
    @ResponseBody
    public String secKill(@RequestParam(value="code",required=true) String code, @RequestParam(value="num",required=true) Integer num,String message){
        Map<String, Object> map = new HashMap<>();
        map.put("code",code);
        map.put("count",num);
        map.put("userId",userId++);
        rabbitTemplate.convertAndSend(mqProperties.getDefaultExchange(),mqProperties.getRouteKey(), map);
        return "选课中，请等待";
    }
}